﻿/********************************************************************
* Copyright (C) 2012 iTouch, Inc (http://www.itouch.com.cn) 
* All rights reserved
* Created by ZhuDongDong <dongdong_82975389@163.com> at 2012-3-30 0:35:32

* 版权所有：浙大网新易盛网络通讯有限公司
* 文件名称：BinarySerializer
* 作    者：朱冬冬(dongdong_82975389@163.com)
* 创建时间：2012-3-30 0:35:32
* 说    明：
*
********************************************************************
$Id: BinarySerializer.cs 27 2012-03-30 01:26:20Z dongdong82975389@gmail.com $
$Rev: 27 $ 
$Author: dongdong82975389@gmail.com $ 
$Date: 2012-03-30 01:26:20 +0000 (Fri, 30 Mar 2012) $
*********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using IDb;

namespace Serialization
{
    /// <summary>
    /// 序列化为二进制数据格式类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BinarySerializer : ISerializer
    {
        /// <summary>
        /// 将对象序列为以字符串表示的二进制数据
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string Serialize<T>(T obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                byte[] bs = ms.GetBuffer();
                string result = Convert.ToBase64String(bs); //使用Base64获得字符串
                //string result = (new UnicodeEncoding()).GetString(bs, 0, bs.Length);  //使用UnicodeEncoding获得字符
                ms.Flush();
                return result;
            }
        }

        /// <summary>
        /// 对字符串表示的二进制数据进行还原为指定的对象
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public T Deserialize<T>(string input)
        {
            byte[] bt = Convert.FromBase64String(input);
            //byte[] bt = (new UnicodeEncoding()).GetBytes(input); 
            using (MemoryStream ms = new MemoryStream(bt))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                T obj = (T)formatter.Deserialize(ms); //反序列化
                ms.Close();
                return obj;
            }
        }
    }
}